package java427;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args){
        //创建服务器Socker对象
        ServerSocket serverSocket=null;
        //声明客户端Socker对象，表示哪一个客户端与服务器建立连接
        Socket clientSocket=null;
        InetAddress ia=null;

        BufferedReader in=null;

        PrintWriter out=null;
        try {
            //创建服务器Socker
            serverSocket=new ServerSocket(8888);
            System.out.println("服务器已启动，正在侦听8888端口，等待客户端连接请求！");
            clientSocket=serverSocket.accept();
            ia=clientSocket.getInetAddress();
            String ip=ia.getCanonicalHostName();//获取远程客户端IP地址
            int poat=clientSocket.getPort();//获取远程端口号
            System.out.println(ip+":"+"客户端已经成功与服务器建立连接，可以通信了！");

            in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"UTF-8"));
            String line=in.readLine();
            System.out.println(line);

            String content="Hello！Client,找我有什么事呢？";
            out=new PrintWriter(clientSocket.getOutputStream(),true);
            out.println(content);
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (clientSocket != null) {
                try {
                    clientSocket.close();
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}